#include "dbTree.h"
#include "dbTag.h"
#include "dbBase.h"

namespace db
{

TreeVertex::TreeVertex(int id, TreeVertex* parent)
{
  /* some initializations */
  ID = id;
  Parent = parent ? parent : this;
  Date = time(NULL);
  Title = "";
  Text = "";

  /* Children[0] is a place for successor's pointer.
     As long as it points NULL, Vertex is a leaf - last post in current line */
  Children.push_back(NULL);
}

TreeVertex::~TreeVertex()
{
  for (int i = 1; i < Parent->Children.size(); i++)
  {
    if (Parent->Children[i] == this)
    {
      Parent->Children[i] = Parent->Children[Parent->Children.size()-1];
      Parent->Children.pop_back();
      break;
    }
  }

  if (Parent->Children[0] == this)
    Parent->Children[0] = NULL;

  for (int i = 0; i < Children.size(); i++)
    if (Children[i])
      delete Children[i];
}

void TreeVertex::setTitle(string title)
{
  Title = title;
}

void TreeVertex::setText(string text)
{
  Text = text;
}

void TreeVertex::setDate(time_t date)
{
  Date = date;
}

void TreeVertex::addTag(string tag)
{
  Tag *t = Base::getTag(tag);
  for (int i = 0; i < Tags.size(); i++)
    if (*Tags[i] == tag)
      return;

  Tags.push_back(t);
  t->addAppear(this);
}

void TreeVertex::remTag(string tag)
{
  for (int i = 0; i < Tags.size(); i++)
  {
    if (*Tags[i] == tag)
    {
      Tags[i]->remAppear(this);
      Tags[i] = Tags[Tags.size()-1];
      Tags.pop_back();
    }
  }
}

int TreeVertex::getID()
{
  return ID;
}

time_t TreeVertex::getDate()
{
  return Date;
}

string TreeVertex::getTitle()
{
  return Title;
}

string TreeVertex::getText()
{
  return Text;
}

int TreeVertex::getBranchCount()
{
  return Children.size();
}

int TreeVertex::getTagsCount()
{
  return Tags.size();
}

string TreeVertex::getTag(int id)
{
  if (id < Tags.size())
    return Tags[id]->getName();
  else
    return Tags[Tags.size()-1]->getName();
}

};